//
//  ShouKuanJiLuViewController.m
//  ShouKuang
//
//  Created by CodeYY on 2019/5/29.
//  Copyright © 2019 CodeYY. All rights reserved.
//

#import "ShouKuanJiLuViewController.h"
#import "CollectionRecordsCell.h"
#import "YYSelectedView.h"
#import "RCalendarPickerView.h" // The calendar
#import "RClockPickerView.h" // A clock dial effect
#import "DateHelper.h" // Time processing with the help of the class
#import "PGDatePickManager.h"

@interface ShouKuanJiLuViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIView *sortView; //筛选
@property(nonatomic, strong)NSMutableArray *dataArray;

// 搜索
@property (nonatomic, weak)UIView *searchView;
@property (nonatomic, strong)UITextField *textField;

// 时间选择
@property (nonatomic, weak)UIView *timeSortView;

// 类型选择
@property (nonatomic, weak)YYSelectedView *selectedView;

@property (nonatomic, copy)NSString *statueStr;// 状态
@property (nonatomic, copy)NSString *startDateStr; // 日期
@property (nonatomic, copy)NSString *endDateStr; // 日期
@end

@implementation ShouKuanJiLuViewController

#pragma mark -LoadView
- (void)viewDidLoad {
    [super viewDidLoad];
    _statueStr = @"全部"; // 代表全部；
    self.dataArray = [NSMutableArray arrayWithArray:@[@"",@"",@"",@"",@"",@"",@"",@"",@""]];
    // 导航栏
    [self initNavBar];
    [self initSortView];
    [self initTableView];
    // contView
 
    
    // Do any additional setup after loading the view.
}

-(void)initNavBar
{
    WEAKSELF
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"nav_back_red"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"返回" forState:UIControlStateNormal];
    [leftBtn setTitleColor:YYRGB(129, 129, 129) forState:UIControlStateNormal];
    [leftBtn jk_setImagePosition:LXMImagePositionLeft spacing:5];
    [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    self.title = @"收款记录";
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.tag = 1002;
    [[searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(UIButton *x) {
        [weakSelf sortAction:x];
    }];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitle:@"取消" forState:UIControlStateSelected];
    [searchBtn setTitleColor:YYRGB(179, 179, 179) forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
}

-(void)initSortView
{
    WEAKSELF
    UIView *sortView = [UIView new];
    sortView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:sortView];
    _sortView = sortView;
    [sortView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(70);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *leftSortBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *rightSortBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    [leftSortBtn setImage:[UIImage imageNamed:@"arrow_gray"] forState:UIControlStateNormal];
    [leftSortBtn setImage:[UIImage imageNamed:@"arrow_red"] forState:UIControlStateSelected];
    [leftSortBtn setTitle:@"类型" forState:UIControlStateNormal];
    [leftSortBtn setTitleColor:YYRGB(129, 129, 129) forState:UIControlStateNormal];
    [leftSortBtn setTitleColor:YYRGB(227, 107, 99) forState:UIControlStateSelected];
    [leftSortBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [leftSortBtn jk_setImagePosition:LXMImagePositionRight spacing:5];
    leftSortBtn.tag = 1000;
    [[leftSortBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton * x) {
        [weakSelf sortAction:x];
    }];
    [sortView addSubview:leftSortBtn];
    [leftSortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.centerY.offset(0);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];
    
    [rightSortBtn setImage:[UIImage imageNamed:@"arrow_gray"] forState:UIControlStateNormal];
    [rightSortBtn setImage:[UIImage imageNamed:@"arrow_red"] forState:UIControlStateSelected];
    [rightSortBtn setTitle:@"创建日期" forState:UIControlStateNormal];
    [rightSortBtn setTitleColor:YYRGB(129, 129, 129) forState:UIControlStateNormal];
    [rightSortBtn setTitleColor:YYRGB(227, 107, 99) forState:UIControlStateSelected];
    [rightSortBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [rightSortBtn jk_setImagePosition:LXMImagePositionRight spacing:5];
    rightSortBtn.tag = 1001;
    [[rightSortBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton * x) {
        [weakSelf sortAction:rightSortBtn];
    }];
    [sortView addSubview:rightSortBtn];
    [rightSortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftSortBtn.mas_right).offset(30);
        make.centerY.offset(0);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    UIView *line = [UIView new];
    [sortView addSubview:line];
    line.backgroundColor =  YYRGB(218, 218, 218);
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(1);
    }];
    
}
- (void)initTableView
{
    WEAKSELF
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView = tableView;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.rowHeight = 90;
    [self.view addSubview:tableView];
//    tableView.backgroundColor = [UIColor clearColor];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.sortView.mas_bottom).offset(0);
        make.bottom.equalTo(self.view);
    }];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.emptyDataSetSource = self;
    tableView.emptyDataSetDelegate = self;
    [tableView registerNib:[UINib nibWithNibName:@"CollectionRecordsCell" bundle:nil] forCellReuseIdentifier:@"CollectionRecordsCells"];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 40)];
    headView.backgroundColor = YYRGB(250, 250, 250);

    UILabel *lab = [UILabel new];
    [headView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    lab.text = @"共10笔，总金额10000元";
    lab.font = [UIFont systemFontOfSize:14];
    lab.textColor = [UIColor lightGrayColor];
    tableView.tableHeaderView = headView;
    
}

#pragma mark -Action
-(void)sortAction:(UIButton *)btn
{
    btn.selected = !btn.selected;
    // 先移除其他的遮罩视图
    if (_selectedView) {
        [_selectedView removeFromSuperview];
    }
    if (_timeSortView) {
        [_timeSortView removeFromSuperview];
    }
    if (_searchView) {
        [_searchView removeFromSuperview];
    }
   
    ((UIButton *)[self.view viewWithTag:1000]).selected =  btn.tag != 1000 ? NO : btn.selected;
    ((UIButton *)[self.view viewWithTag:1001]).selected =  btn.tag != 1001 ? NO : btn.selected;
    ((UIButton *)[self.navigationController.navigationBar viewWithTag:1002]).selected =  btn.tag != 1002 ? NO : btn.selected;
    if (!btn.selected) return;
    
    
    switch (btn.tag -1000) {
        case 0: // 点击搜索
        {
            [self.selectedView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.offset(0);
                make.top.equalTo(self.sortView.mas_bottom);
            }];
        }
            break;
        case 1: // 点击创建日期
        {
            [self.timeSortView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.offset(0);
                make.top.equalTo(self.sortView.mas_bottom);
            }];

        }
            break;
        case 2: // 点击
        {
            [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.offset(0);
                make.top.equalTo(self.sortView.mas_bottom);
            }];
        }
            break;
        default:
            break;
    }
}


#pragma mark -TableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectionRecordsCells" forIndexPath:indexPath];
    [cell configUIWithData:nil];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
}

#pragma mark-Lazy
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UIView *)searchView
{
    __weak typeof(self) weakSelf = self;
    if (!_searchView) {
        UIView *searchView = [[UIView alloc] init];
        _searchView = searchView;
        [self.view addSubview:self.searchView];
        searchView.backgroundColor = [UIColor clearColor];
        
        
        UIView *contentView = [UIView new];
        contentView.backgroundColor = [UIColor whiteColor];
        [searchView addSubview:contentView];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.offset(0);
            make.height.mas_equalTo(60);
        }];
        UITextField *textField = [[UITextField alloc] init];

        // 搜索按钮
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [contentView addSubview:searchBtn];
        [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-20);
            make.centerY.offset(0);
            make.size.mas_equalTo(CGSizeMake(70, 30));
        }];
        [searchBtn setTitle:@"搜索" forState:(UIControlStateNormal)];
        searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        searchBtn.layer.cornerRadius = 8;
        searchBtn.layer.masksToBounds = YES;
        searchBtn.backgroundColor = YYRGB(219, 67, 57);
        [[searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            NSString *searchStr = textField.text;
            if (!searchStr.length) {
                [weakSelf.view makeToast:@"查询内容不可为空"];
                return;

            }
                [weakSelf sortAction:nil];
            [weakSelf.view makeToast:@"正在查询请稍等"];
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.tableView reloadData];
        }];
        
        
        // 搜索框
        [contentView addSubview:textField];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.centerY.offset(0);
            make.right.equalTo(searchBtn.mas_left).offset(-12);
            make.height.mas_equalTo(33);
        }];
        _textField = textField;
        textField.delegate = self;
        textField.layer.masksToBounds = YES;
        textField.layer.cornerRadius = 8;
        textField.layer.borderColor = YYRGB(218, 218, 218).CGColor;
        textField.layer.borderWidth = 1;
        textField.backgroundColor = YYRGB(244, 244, 244);
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 2, 16, 16)];
        UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 32, 20)];
        [bg addSubview:imageView];
        imageView.image = [UIImage imageNamed:@"search"];
        
        UIView *line = [UIView new];
        [bg addSubview:line];
        line.backgroundColor =  YYRGB(218, 218, 218);
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(imageView);
            make.left.equalTo(imageView.mas_right).offset(5);
            make.size.mas_equalTo(CGSizeMake(1, 15));
        }];
        
        textField.leftView = bg;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.leftViewMode = UITextFieldViewModeAlways;
        
        UIButton *shadowBtn = [self createShadowBtn];
        [searchView addSubview:shadowBtn];
        [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.top.equalTo(contentView.mas_bottom);
        }];
    }
    return _searchView;
}

-(UIView *)timeSortView
{
    if (!_timeSortView) {
        WEAKSELF
        UIView *timeSortView = [UIView new];
        [self.view addSubview:timeSortView];
        timeSortView.backgroundColor = [UIColor clearColor];
        _timeSortView = timeSortView;
        
        UIView *contentView = [UIView new];
        contentView.backgroundColor = [UIColor whiteColor];
        [timeSortView addSubview:contentView];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.offset(0);
            make.height.mas_equalTo(50);
        }];
        
        UIView *leftView = [self createTimeSortBtn:YES];
        [contentView addSubview:leftView];
        [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.offset(8);
            make.bottom.offset(-8);
            make.width.mas_equalTo(120);
        }];
        
        UIView *line = [UIView new];
        [contentView addSubview:line];
        line.backgroundColor =  YYRGB(218, 218, 218);
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftView.mas_right).offset(5);
            make.centerY.offset(0);
            make.size.mas_equalTo(CGSizeMake(15, 1));
        }];
        
        UIView *rightView = [self createTimeSortBtn:NO];
        [contentView addSubview:rightView];
        [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(8);
            make.bottom.offset(-8);
            make.width.mas_equalTo(120);
            make.left.equalTo(line.mas_right).offset(5);
        }];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.layer.masksToBounds = YES;
        sureBtn.layer.cornerRadius = 8;
        sureBtn.layer.borderColor = [UIColor blueColor].CGColor;
        sureBtn.layer.borderWidth = 1;
        [contentView addSubview:sureBtn];
        [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(-10);
            make.size.mas_equalTo(CGSizeMake(75, 30));
        }];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        
        [sureBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            __block  NSString *startTime;
            __block  NSString *endTime;
            [leftView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[UILabel class]]) {
                    startTime = [(UILabel *)obj text];
                    *stop = YES;
                }
            }];
            [rightView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[UILabel class]]) {
                    endTime = [(UILabel *)obj text];
                    *stop = YES;
                }
            }];
            if (!startTime.length) {
                [self.view makeToast:@"请选择开始时间"];
                return ;
            }
            if (!endTime.length) {
                [self.view makeToast:@"请选择结束时间"];
                return ;
            }
            if ([[NSDate dateWithString:startTime format:@"yyyyMMdd"] timeIntervalSince1970] >= [[NSDate dateWithString:endTime format:@"yyyyMMdd"] timeIntervalSince1970]) {
                [self.view makeToast:@"结束时间要大于开始时间"];
                return ;
            }
            weakSelf.startDateStr = startTime;
            weakSelf.endDateStr = endTime;
            [self.view makeToast:@"正在查询数据，请稍等"];
            [weakSelf sortAction:nil];
        }];
        UIButton *shadowBtn = [self createShadowBtn];
        [timeSortView addSubview:shadowBtn];
        [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.top.equalTo(contentView.mas_bottom);
        }];
    }
    return _timeSortView;
    
}
-(UIButton *)createShadowBtn
{
    WEAKSELF
    UIButton *shadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shadowBtn.backgroundColor = [UIColor blackColor];
    shadowBtn.alpha = 0.3;
    [[shadowBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [weakSelf sortAction:nil];
    }];
    return shadowBtn;
}

-(UIView *)createTimeSortBtn:(BOOL)left
{
    WEAKSELF
    UIView *sortBtnView = [UIView new];
    sortBtnView.layer.masksToBounds = YES;
    sortBtnView.layer.cornerRadius = 8;
    sortBtnView.layer.borderColor = YYRGB(218, 218, 218).CGColor;
    sortBtnView.layer.borderWidth = 1;
    
    UIImageView *imgView = [UIImageView new];
    imgView.image = [UIImage imageNamed:@"date"];
    [sortBtnView addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-8);
        make.centerY.offset(0);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        
    }];
    UILabel *lab = [UILabel new];
    [sortBtnView addSubview:lab];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.font = [UIFont systemFontOfSize:14];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(8);
        make.right.equalTo(imgView.mas_left).offset(-8);
        make.top.bottom.offset(0);
    }];
    lab.text = left ? _startDateStr : _endDateStr;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortBtnView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
        PGDatePicker *datePicker = datePickManager.datePicker;
        datePicker.datePickerMode = PGDatePickerModeDate;
        //        datePickManager.titleLabel.text = @"PGDatePicker";
        //设置半透明的背景颜色
        datePickManager.isShadeBackground = true;
        //设置头部的背景颜色
        datePickManager.headerViewBackgroundColor = FZVCbackgroundColor;
        //设置线条的颜色
        datePicker.lineBackgroundColor = FZSeporateLineColor;
        //设置选中行的字体颜色
        datePicker.textColorOfSelectedRow = [UIColor redColor];
        //设置未选中行的字体颜色
        datePicker.textColorOfOtherRow = FZZhongSe;
        //设置取消按钮的字体颜色
        datePickManager.cancelButtonTextColor = [UIColor blackColor];
        //设置取消按钮的字
        datePickManager.cancelButtonText = @"取消";
        //设置取消按钮的字体大小
        datePickManager.cancelButtonFont = [UIFont boldSystemFontOfSize:17];
        
        //设置确定按钮的字体颜色
        datePickManager.confirmButtonTextColor = [UIColor redColor];
        //设置确定按钮的字
        datePickManager.confirmButtonText = @"确认";
        //设置确定按钮的字体大小
        datePickManager.confirmButtonFont = [UIFont boldSystemFontOfSize:17];
        
        [self presentViewController:datePickManager animated:false completion:nil];
        
        datePicker.selectedDate = ^(NSDateComponents *dateComponents) {
            NSLog(@"dateComponents = %@", dateComponents);
            NSString * timeStr = [NSString stringWithFormat:@"%02d%02d%02d",dateComponents.year,dateComponents.month,dateComponents.day];
            lab.text = timeStr;
        };
    }];
    
    return sortBtnView;
}
-(YYSelectedView *)selectedView
{
    WEAKSELF
    if (!_selectedView) {
        YYSelectedView *selectedView = [YYSelectedView yySelectedView:nil selectBlock:^(NSString *selectContent) {
            if (selectContent) {
                weakSelf.statueStr = selectContent;
                [self.view makeToast:@"正在查询请稍等"];
                [weakSelf.tableView reloadData];
            }
            [weakSelf sortAction:nil];

        }];
        _selectedView = selectedView;
        [self.view addSubview:selectedView];
    }
    
    NSArray *dataAry = @[@{@"imgName":@"shk",
                           @"title":@"收款"
                           },
                         @{
                             @"imgName":@"撤销",
                             @"title":@"撤销"
                             },
                         @{
                             @"imgName":@"refund",
                             @"title":@"退款"
                             },
                         @{
                             @"imgName":@"全部",
                             @"title":@"全部"
                             }
                         ];
    _selectedView.defaultStr = _statueStr;
    [_selectedView updateDataSource:dataAry];
    return _selectedView;
}

//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
//{
//    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"未找到相关记录" attributes:@{
//                                                                                                 NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
//    return str;
//
//}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"未找到相关记录" attributes:@{
                                                                                                 NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    return str;
}
/**
 Asks the data source for the image of the dataset.
 
 @param scrollView A scrollView subclass informing the data source.
 @return An image for the dataset.
 */
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"failure"];
}


@end
